/**
 * 保存blob
 * @param {Blob} blob
 * @param {string} [fileName]
 */
const saveBlob = (blob, fileName = 'file') => {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  a.click()
  URL.revokeObjectURL(url)
}

/**
 *  原生canvas 导出为svg
 * @param {HTMLCanvasElement} canvas
 */
const exportCanvasToSVG = (canvas, fileName = 'svg.svg') => {
  canvas.toBlob((blob) => {
    saveBlob(blob, fileName)
  }, 'image/svg+xml')
}
/**
 *  fbric.Canvas 导出为SVG
 * @param {fabric.Canvas} canvas
 */
const exportFabricToSVG = (canvas, fileName = 'svg.svg') => {
  const svg = canvas.toSVG()
  const blob = new Blob([svg], { type: 'image/svg+xml' })
  saveBlob(blob, fileName)
}
/**
 *  fbric.Canvas 导出为SVG，浏览器不显示下载记录
 * @param {fabric.Canvas} canvas
 */
const exportFabricToSVG2 = async (canvas, fileName = 'svg.svg') => {
  const svg = canvas.toSVG()
  const blob = new Blob([svg], { type: 'image/svg+xml' })
  try {
    const fileHandle = await window.showSaveFilePicker({
      suggestedName: fileName,
      types: [
        {
          description: 'SVG Files',
          accept: { 'image/svg+xml': ['.svg'] },
        },
      ],
      excludeAcceptAllOption: true,
    })

    // 将 blob 写入文件
    const writable = await fileHandle.createWritable()
    await writable.write(blob)
    await writable.close()
  } catch (err) {
    console.error('用户取消保存或保存失败:', err)
  }
}

/**
 * 读取svg文件
 * @returns {Promise<String>} svg字符串
 */
const readSvgFile = async () => {
  let svg = ''
  if (window.showOpenFilePicker) {
    try {
      const [fileHandle] = await window.showOpenFilePicker({
        types: [
          {
            description: 'SVG文件',
            accept: {
              'image/svg+xml': ['.svg'],
            },
          },
        ],
        excludeAcceptAllOption: true,
      })
      const file = await fileHandle.getFile()
      svg = await file.text()
      return svg
    } catch (err) {
      console.error('用户取消选择或选择失败:', err)
    }
  } else {
    return new Promise((resolve, reject) => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.svg'
      input.onchange = async () => {
        const file = input.files[0]
        svg = await file.text()
        resolve(svg)
      }
      input.click()
    })
  }
}

/**
 * 保存json
 * @param {String} json
 */
const saveJson = (json, fileName = 'export.json') => {
  const blob = new Blob([json], { type: 'application/json' })
  saveBlob(blob, fileName)
}
/**
 * 使用文件系统读取json并包裹在promise中返回
 * @returns {Promise<String>}
 */
const readJson = async () => {
  let json
  if ('showOpenFilePicker' in window) {
    try {
      const [fileHandle] = await window.showOpenFilePicker({
        types: [
          {
            description: 'JSON file',
            accept: { 'application/json': ['.json'] },
          },
        ],
        excludeAcceptAllOption: true,
      })
      const fileData = await fileHandle.getFile()
      json = await fileData.text()
      return json
    } catch (error) {
      console.error('用户取消读取或读取失败:', error)
    }
  } else {
    return new Promise((resolve, reject) => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.json'
      input.onchange = async () => {
        const file = input.files[0]
        if (file && file.type === 'application/json') {
          json = await file.text()
          resolve(json)
        }
      }
      input.click()
    })
  }
}

export {
  saveBlob,
  exportCanvasToSVG,
  exportFabricToSVG,
  exportFabricToSVG2,
  readSvgFile,
  saveJson,
  readJson,
}
